<template>
  <div class="flex flex-wrap gap-4">
    <el-card style="font-size: 15px;font-weight: bold;margin-bottom: 10px" shadow="always"><span style="color: #535bf2">|</span> 商品列表页
    </el-card>
  </div>
  <div class="productList" style="padding-top: 30px">
    <!-- 商品搜索表单 -->
    <el-form style="margin-left: 15px " :inline="true" :model="productSearchQuery">
    </el-form>
    <el-button type="primary" @click="addView">添加商品</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>

    <el-table
        :data="productList"
        style="width: auto"
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" show-overflow-tooltip/>
      <el-table-column type="index" label="序号" width="100" show-overflow-tooltip/>
      <el-table-column prop="productName" label="商品名" width="200" show-overflow-tooltip></el-table-column>
      <el-table-column label="图片地址" width="400">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.productImage"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="价格" width="100" show-overflow-tooltip/>
      <el-table-column prop="productType" label="商品类型" width="300" show-overflow-tooltip/>
      <el-table-column prop="productDesc" label="商品描述" width="200" show-overflow-tooltip/>
      <el-table-column prop="createTime" label="创建时间" width="150" show-overflow-tooltip/>
      <el-table-column prop="productBrand" label="品牌" width="250" show-overflow-tooltip/>

      <el-table-column style="" label="操作" width="230">
        <template #default="scope">
          <el-button type="primary" @click="view(scope.row.id)">详情</el-button>
          <el-button type="success" @click="editView(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="delProduct(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination style="justify-content: center;margin-top: 10px"
                   background
                   layout="prev, pager,next"
                   :page-size=pageSize
                   :total=total
                   @current-change="toPage"
                   @prev-click="toPage"
                   @next-click="toPage"
    />

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="1000px" draggable="true" center>
      <el-form ref="addRefForm" :model="productQuery" label-width="auto" style="max-width: 800px">
        <el-form-item label="商品名：" prop="productName">
          <el-input v-if="productQuery.id == null" v-model="productQuery.productName" placeholder="请输入商品名"/>
          <span class="detail" v-else>{{ productQuery.productImage }}</span>
        </el-form-item>
        <el-form-item label="商品图片：" prop="productImage">
          <el-upload
              v-if="productQuery.id == null"
              v-model="productQuery.productImage"
              list-type="picture-card"
              action="http://localhost:8080/upload"
              multiple
              :limit="3"
              :on-success="handleAvatarSuccess"
          >
          </el-upload>
          <span class="detail" v-else>
                <img :src="productQuery.productImage" alt="商品图片" class="product-image">
      </span>
        </el-form-item>
        <el-form-item label="价格：" prop="price">
          <el-input v-if="productQuery.id == null" v-model="productQuery.price" placeholder="请输入价格"/>
          <span class="detail" v-else>{{ productQuery.price }}</span>
        </el-form-item>
        <el-form-item  label="商品类型：">
          <el-select style="width: 150px"
                     v-if="productQuery.id==null"
                     v-model="productQuery.productType"
                     placeholder="请选择商品类型"
                     @click="loadProductType"
                     clearable>
            <el-option
                v-for="item in productTypeOptions"
                :key="item.id"
                :label="item.productTypeName"
                :value="item.id"/>
          </el-select>
          <span class="detail" v-else>{{ productQuery.id }}</span>
        </el-form-item>
        <el-form-item label="商品描述：" prop="productDesc">
          <el-input v-if="productQuery.id == null" v-model="productQuery.productDesc" placeholder="请输入商品描述"/>
          <span class="detail" v-else>{{ productQuery.productDesc }}</span>
        </el-form-item>
        <el-form-item  label="品牌：">
          <el-select style="width: 150px"
                     v-if="brandQuery.id==null"
                     v-model="productQuery.productBrand"
                     placeholder="请选择品牌"
                     @click="loadBrand"
                     clearable>
            <el-option
                v-for="item in brandOptions"
                :key="item.id"
                :label="item.brandName"
                :value="item.id"/>
          </el-select>
          <span class="detail" v-else>{{ brandQuery.id }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="productQuery.id==null" type="primary" @click="addProductSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="1000px" draggable="true" center>
      <el-form ref="addRefForm" :model="editProductQuery" label-width="auto" style="max-width: 800px">
        <el-form-item label="商品名：" prop="productName">
          <el-input v-model="editProductQuery.productName"/>
        </el-form-item>
        <el-form-item label="商品图片：">
          <el-upload
              v-model="editProductQuery.productImage"
              :src="editProductQuery.productImage"
              list-type="picture-card"
              action="http://localhost:8080/upload"
              multiple
              :limit="3"
              :on-success="handleAvatarSuccess"
          >
            <el-image
                style="width: 100px; height: 100px"
                :src="editProductQuery.productImage"
            ></el-image>
          </el-upload>
        </el-form-item>
        <el-form-item label="价格：" prop="price">
          <el-input v-model="editProductQuery.price"/>
        </el-form-item>
        <el-form-item  label="商品类型：">
          <el-select style="width: 150px"
                     v-if="productQuery.id==null"
                     v-model="productQuery.productType"
                     placeholder="请选择商品类型"
                     @click="loadProductType"
                     clearable>
            <el-option
                v-for="item in productTypeOptions"
                :key="item.id"
                :label="item.productTypeName"
                :value="item.id"/>
          </el-select>
          <span class="detail" v-else>{{ productQuery.id }}</span>
        </el-form-item>
        <el-form-item label="商品描述：" prop="productDesc">
          <el-input v-model="editProductQuery.productDesc"/>
        </el-form-item>
      <el-form-item  label="品牌：">
        <el-select style="width: 150px"
                   v-if="brandQuery.id==null"
                   v-model="brandQuery.id"
                   placeholder="请选择品牌"
                   @click="loadBrand"
                   clearable>
          <el-option
              v-for="item in brandOptions"
              :key="item.id"
              :label="item.brandName"
              :value="item.id"/>
        </el-select>
        <span class="detail" v-else>{{ brandQuery.id }}</span>
      </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editProductSubmit">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {doDelete, doGet, doPost, doPut} from "../http/httpRequest.js";
import {messageConfirm, messageTip} from "../util/util.js";
import qs from "qs";

export default {
  name: "ProductView",
  inject: ['reload'],
  data() {
    return {
      productList: [],
      dialogVisible: false,
      productQuery: {
        productImage: '',
        productType: '', // 新增初始化商品类型

      },
      brandQuery:{},
      pageSize: 0,
      total: 0,
      productIdArray: [],
      editDialogVisible: false,
      editProductQuery: {},
      selectedProductIds: [],
      // 用于绑定商品搜索框中的数据
      productSearchQuery: {},
      // 商品类型下拉框的选项数据
      productTypeOptions: [],
      // 品牌下拉框的选项数据
      brandOptions: [],
    }
  },
  mounted() {
    this.loadProductList(1);
    this.loadProductOptions();
  },
  methods: {
    toPage(current) {
      this.loadProductList(current);
    },
    handleSelectionChange(productItemArray) {
      this.productIdArray = [];
      productItemArray.forEach((product) => {
        this.productIdArray.push(product.id);
      });
      this.selectedProductIds = this.productIdArray.slice();
    },
    loadProductList(current) {
      doGet("/admin/product", {
        current: current
      }).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.productList = resp.data.data.list;
          this.pageSize = resp.data.data.pageSize;
          this.total = resp.data.data.total;
        }
      });
    },
    loadProductType() {
      doGet("/admin/ProductType", {current: "1"}).then((resp) => {
        console.log(resp.data.data.list)
        if (resp.data.code === 200) {
          // 将后端的数据信息赋值给 productTypeOptions,数据绑定，后续可以在下拉框中取出
          this.productTypeOptions = resp.data.data.list
        }
      })
    },
    loadBrand() {
      doGet("/admin/brand", {current: "1"}).then((resp) => {
        console.log(resp.data.data.list)
        if (resp.data.code === 200) {
          // 将后端的数据信息赋值给 brandOptions,数据绑定，后续可以在下拉框中取出
          this.brandOptions = resp.data.data.list
        }
      })
    },
    addView() {
      this.productQuery = {};
      this.dialogVisible = true;
    },
    view(id) {
      doGet("/admin/product/" + id).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.productQuery = resp.data.data;
          this.dialogVisible = true;
        }
      });
    },
    editView(id) {
      doGet("/admin/product/" + id).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.editProductQuery = resp.data.data;
          this.editDialogVisible = true;
        }
      });
    },
    delProduct(id) {
      messageConfirm('是否删除该商品？').then(() => {
        doDelete("/admin/product/" + id).then((resp) => {
          if (resp.data.code === 200) {
            messageTip('删除成功', 'success');
            this.reload();
          }
        });
      });
    },
    batchDel() {
      if (this.selectedProductIds.length === 0) {
        messageTip('请先选择要批量删除的商品', 'warning');
        return;
      }
      messageConfirm('是否确认批量删除选中的商品？').then(() => {
        const deletePromises = this.selectedProductIds.map((id) => {
          return doDelete("/admin/product?method=delete", {
            id: id
          });
        });
        Promise.all(deletePromises).then((results) => {
          let allSuccess = true;
          results.forEach((resp) => {
            if (resp.data.code!== 200) {
              allSuccess = false;
            }
          });
          if (allSuccess) {
            messageTip('批量删除成功', 'success');
            this.reload();
          } else {
            messageTip('部分商品删除失败，请查看详情', 'error');
          }
        });
      });
    },
    addProductSubmit() {
      doPost("/admin/product/save", this.productQuery).then((resp) => {
        if (resp.data.code === 200) {
          this.dialogVisible = false;
          messageTip("添加成功", "success");
          this.reload();
        } else {
          messageTip("添加失败", "error");
        }
      });
    },
    editProductSubmit() {
      doPut("/admin/product", this.editProductQuery).then((resp) => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.editDialogVisible = false;
          messageTip("修改成功！", "success");
          this.reload();
        }
      });
    },
    handleAvatarSuccess(res, file) {
      console.log(res.data)
      this.productQuery.productImage = res.data
      this.editProductQuery.productImage = res.data

    },
    // 加载品牌下拉框的选项数据
    loadProductOptions() {
      doGet("/admin/product?method=findAll", {current: "1"}).then((resp) => {
        console.log(resp.data.data.list);
        if (resp.data.code === 200) {
          this.productOptions = resp.data.data.list;
        }
      })
    },
    // 商品搜索功能
    // onSearch() {
    //   console.log(this.productSearchQuery.productTypeId);
    //   console.log(this.productSearchQuery.productBrandId);
    //   doGet("/product?method=searchByCondition", {
    //     productTypeId: this.productSearchQuery.productTypeId,
    //     productBrandId: this.productSearchQuery.productBrandId
    //   }).then((resp) => {
    //     console.log(resp);
    //     if (resp.data.code === 200) {
    //       this.productList = resp.data.data;
    //       this.reload();
    //     }
    //   })
    // },
    // // 重置商品搜索表单数据
    // onReset() {
    //   this.productSearchQuery = {};
    // }
  }
}
</script>

<style scoped>
.productList {
  width: auto;
  height: auto;
  background-color: #ffffff;
}

.detail {
  background-color: #f5f7fa;
  width: 100%;
  padding-left: 15px;
}

.product-image {
  max-width: 100%;
  max-height: 100%;
  display: block;
}
</style>